import os
import sys
import time
from util import *
from db import *


def fetch_stock_data(stocknum="000100",targetdate="", period="daily"):
    endday = ""
    startday = begin_day
    print (startday)

    if (not targetdate):
        endday = get_today_date()
    else:
        endday = targetdate
    print (endday)

    dftemp = ak.stock_zh_a_hist(stocknum,
                            period=period,
                            start_date=startday,
                            end_date=endday,
                            adjust="")
    return dftemp


def init_stock_database(stocknum="000100", period="daily"):
    collectionName = str(stocknum) + str(period)
    collection_name = "zh" + stocknum + "_" + period
    collection = mydb.db[collection_name]
    print (collection_name)
    dftemp = fetch_stock_data(stocknum,"",period)
    dftemp.iloc[:, 0] = dftemp.iloc[:, 0].astype(str)
    data_dict = dftemp.to_dict(orient='records')
    collection.insert_many(data_dict)
    return

def init_stock_database_all(stocknum="000100"):
    init_stock_database(stocknum,"daily")
    init_stock_database(stocknum,"weekly")
    init_stock_database(stocknum,"monthly")
    pass

def init_from_config():
    stocklist = make_stock_list()
    for stock in stocklist:
        init_stock_database_all(stock)

def update_stock_all():
    print ("begin to update stock!!\n")
    collection_names = mydb.db.list_collection_names()
    for cname in collection_names:
        #print (cname)
        update_stock(cname)

def update_stock(cname):
    lastestday = get_col_lastest_day(cname)
    stocknum = cname.split('_')[0].replace("zh","")
    period = cname.split('_')[1]
    delete_last_record(cname)
    dftemp = ak.stock_zh_a_hist(stocknum,
                        period=period,
                        start_date=lastestday.replace("-",""),
                        end_date=get_today_date(),
                        adjust="")
    collection = mydb.db[cname]
    dftemp.iloc[:, 0] = dftemp.iloc[:, 0].astype(str)
    print (dftemp)
    data_dict = dftemp.to_dict(orient='records')
    collection.insert_many(data_dict)
    print (cname, "Update Success!!")

def delete_last_record(cname):
    wc = mydb.db[cname]
    last_two_records = wc.find().sort('_id', -1).limit(1)
    for r in last_two_records:
        wc.delete_one({'_id': r['_id']})

def get_col_lastest_day(colname):
   wc = mydb.db[colname]
   last_record = wc.find().sort('_id', -1).limit(1)
   for r in last_record:
       del r['_id']
       df = pd.DataFrame(r, index=[0])
       return (df.iloc[0, 0])

if __name__ == '__main__':
    args = sys.argv
    if len(args) < 2:
        print ("parameters is not enough!!")
    else:
        funtype = args[1]
        if funtype == "initbyconfig":
            print ("will init by config!!")
            init_from_config()

        elif funtype == "initybycode":
            print ("will init by Code")
            if len(args) < 3:
                print ("parameter is not enough!!")
            else:
                stocknum = args[2]
                print ("stocknum is", stocknum)

        elif funtype == "update":
            print ("update database!!")
            update_stock_all()

        elif funtype == "drop":
            print ("drop database!")
            mydb.dropDatabase()

        elif funtype == "testak":
            print ("test akShare")
            dftemp = fetch_stock_data()
            print (dftemp)

        elif funtype == "debug":
            print ("debug info")
            update_stock("zh000100_weekly")

        else:
            print ("Not Support Functions!!")


